//
//  UIViewController+ Current.m
//  MeeffDylib
//
//  Created by global on 2023/12/11.
//

#import "UIViewController+Current.h"

@implementation UIViewController(Current)

+ (UIViewController *)currentViewController {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [self findTopViewController:rootViewController];
}

+ (UIViewController *)findTopViewController:(UIViewController *)rootViewController {
    if (rootViewController.presentedViewController) {
        // 递归查找最上层的视图控制器
        return [self findTopViewController:rootViewController.presentedViewController];
    }
    else if ([rootViewController isKindOfClass:[UISplitViewController class]]) {
        UISplitViewController *svc = (UISplitViewController *)rootViewController;
        if (svc.viewControllers.count > 0)
            return [self findTopViewController:svc.viewControllers.lastObject];
        else
            return rootViewController;
    }
    else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)rootViewController;
        if (nav.viewControllers.count > 0)
            return [self findTopViewController:nav.topViewController];
        else
            return rootViewController;
    }
    else if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tab = (UITabBarController *)rootViewController;
        if (tab.viewControllers.count > 0)
            return [self findTopViewController:tab.selectedViewController];
        else
            return rootViewController;
    }
    else {
        return rootViewController;
    }
}
@end
